import 'package:flutter/material.dart';

import 'package:provider/provider.dart';
import '../role_model.dart';
import '../role_view_model.dart';

class RoleEditDialog extends StatefulWidget {
  final Role? role;

  const RoleEditDialog({Key? key, this.role}) : super(key: key);

  @override
  State<RoleEditDialog> createState() => _RoleEditDialogState();
}

class _RoleEditDialogState extends State<RoleEditDialog> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _nameController;
  late TextEditingController _codeController;
  late TextEditingController _descriptionController;
  late int _status;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(text: widget.role?.name ?? '');
    _codeController = TextEditingController(text: widget.role?.code ?? '');
    _descriptionController = TextEditingController(text: widget.role?.remark ?? '');
    _status = widget.role?.status ?? 1;
  }

  @override
  void dispose() {
    _nameController.dispose();
    _codeController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Container(
        width: 400,
        padding: const EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                widget.role == null ? '新建角色' : '编辑角色',
                style: Theme.of(context).textTheme.titleLarge,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _nameController,
                decoration: const InputDecoration(
                  labelText: '角色名称 *',
                  hintText: '请输入角色名称',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入角色名称';
                  }
                  if (value.length > 50) {
                    return '角色名称不能超过50个字符';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _codeController,
                decoration: const InputDecoration(
                  labelText: '角色编码 *',
                  hintText: '请输入角色编码',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入角色编码';
                  }
                  if (!RegExp(r'^[A-Za-z0-9_]+$').hasMatch(value)) {
                    return '角色编码只能包含字母、数字和下划线';
                  }
                  if (value.length > 30) {
                    return '角色编码不能超过30个字符';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _descriptionController,
                decoration: const InputDecoration(
                  labelText: '角色描述',
                  hintText: '请输入角色描述',
                  border: OutlineInputBorder(),
                ),
                maxLines: 3,
                validator: (value) {
                  if (value != null && value.length > 200) {
                    return '角色描述不能超过200个字符';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              DropdownButtonFormField<int>(
                value: _status,
                decoration: const InputDecoration(
                  labelText: '状态',
                ),
                items: const [
                  DropdownMenuItem(
                    value: 1,
                    child: Text('启用'),
                  ),
                  DropdownMenuItem(
                    value: 0,
                    child: Text('禁用'),
                  ),
                ],
                onChanged: (value) {
                  if (value != null) {
                    setState(() {
                      _status = value;
                    });
                  }
                },
              ),
              const SizedBox(height: 24),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('取消'),
                  ),
                  const SizedBox(width: 8),
                  ElevatedButton(
                    onPressed: _handleSubmit,
                    child: const Text('保存'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _handleSubmit() async {
    if (_formKey.currentState!.validate()) {
      final viewModel = RoleViewModel();
      final roleData = {
        'name': _nameController.text,
        'code': _codeController.text,
        'status': _status,
        'remark': _descriptionController.text,
      };

      try {
        if (widget.role != null) {
          await viewModel.updateRole(widget.role!.id, roleData);
        } else {
          await viewModel.createRole(roleData);
        }
        if (mounted) {
          Navigator.of(context).pop(true);
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('保存失败：${e.toString()}')),
          );
        }
      }
    }
  }
}